package ServiceTask;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Looper;
import android.support.v4.content.FileProvider;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by 王彦鹏 on 2018-02-08.
 */

public class UpdateControll {
    private Context ctx;
    /* 下载保存路径 */
    private String mSavePath;
    public String appUrl="";
    /* 是否取消更新 */
    public boolean cancelUpdate = false;
    private IDownProgress callback;
    private boolean isInstall=true;
    public String fileName="";


    public UpdateControll(Context ctx, boolean install, IDownProgress callback)
    {
        this.ctx=ctx;
        this.callback=callback;
        this.isInstall=install;
        downloadApk();

    }
    /**
     * 下载apk文件
     */
    private void downloadApk()
    {
        // 启动新线程下载软件
        new downloadApkThread().start();
    }

    /**
     * 下载文件线程
     *
     * @author coolszy
     *@date 2012-4-26
     *@blog http://blog.92coding.com
     */
    private class downloadApkThread extends Thread
    {
        @Override
        public void run()
        {
            Looper.prepare();
            try
            {
                // 判断SD卡是否存在，并且是否具有读写权限
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
                {
                    // 获得存储卡的路径
                    String sdpath = Environment.getExternalStorageDirectory() + "/";
                    mSavePath = sdpath +"download";
                    URL url;
                    try {
                        url = new URL(appUrl);
                    }
                    catch (Exception E) {
                        url = new URL("http://192.168.0.16:804/appfile/app.zip");
                    }
                    // 创建连接
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.connect();
                    // 获取文件大小
                    int length = conn.getContentLength();
                    int progress=0;
                    // 创建输入流
                    InputStream is = conn.getInputStream();

                    File file = new File(mSavePath);
                    // 判断文件目录是否存在
                    if (!file.exists())
                    {
                        file.mkdir();
                    }
                    File apkFile = new File(mSavePath, "app.apk");
                    FileOutputStream fos = new FileOutputStream(apkFile);
                    int count = 0;
                    // 缓存
                    byte buf[] = new byte[1024];
                    // 写入到文件中
                    do
                    {
                        int numread = is.read(buf);
                        count += numread;
                        // 写入文件
                        fos.write(buf, 0, numread);
                        // 计算进度条位置
                        callback.DownProgress(length,count,apkFile.getPath());
                        if (count >= length)
                        {
                            // 下载完成
                            if (isInstall)
                            {
                                installApk(apkFile.getPath());
                            }
                            break;
                        }
                    } while (!cancelUpdate);// 点击取消就停止下载.
                    if (isInstall) {
                        File f = new File(Environment.getExternalStorageDirectory() + "/download", fileName);
                        f.delete();
                    }
                    fos.close();
                    is.close();
                }
                else
                {
                    Toast.makeText(ctx,"未找到SD卡，或没有SD卡读写权限", Toast.LENGTH_SHORT);
                }
            } catch (MalformedURLException e)
            {
                e.printStackTrace();
            } catch (IOException e)
            {
                e.printStackTrace();
            }
            Looper.loop();
        }
    };

    private static String getAppName(Context ctx)
    {
        try {
            PackageManager pm = ctx.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(ctx.getPackageName(), 0);
            String str=pi.packageName;
            return  str;
        }
        catch (Exception e)
        {
            return "";
        }
    }
    /**
     * 安装APK文件
     */
    public void installApk( String fileName)
    {
        try {
            File apkfile = new File(fileName);
            if (!apkfile.exists()) {
                return;
            }
            // 通过Intent安装APK文件
            Intent intent = new Intent(Intent.ACTION_VIEW);
            //判断是否是AndroidN以及更高的版本
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                //String appname=getAppName(ctx);
                String appname="drinkdevice";
                Uri contentUri = FileProvider.getUriForFile(ctx,appname, apkfile);
                intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
            } else {
                intent.setDataAndType(Uri.fromFile(apkfile), "application/vnd.android.package-archive");
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            }

            //intent.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");

            ctx.startActivity(intent);
        }
        catch (Exception E)
        {
            E.printStackTrace();
            Toast.makeText(ctx,E.getMessage(), Toast.LENGTH_SHORT);
        }
    }

}
